import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yang
 * Date: 2022-09-22
 * Time: 18:19
 */
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;

    public MyTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }


}

public class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    Object locker = new Object();

    MyTimer(){
        Thread t = new Thread(()->{
            while (true) {
                synchronized (locker) {
                    try {
                        MyTask task = queue.take();
                        if (task.getTime() > System.currentTimeMillis()) {
                            queue.put(task);

                            long diff = task.getTime() - System.currentTimeMillis();

                            locker.wait(diff);


                        } else {
                            task.getRunnable().run();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            }
        });
        t.start();
    }

    void schedule(Runnable runnable, long delay) throws InterruptedException {

        MyTask task = new MyTask(runnable,delay);
        queue.put(task);
        synchronized (locker){
            locker.notify();
        }
    }




    public static void main(String[] args) throws InterruptedException {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("第一波");
            }
        },3000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("第二波");
            }
        },4000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("第三波");
            }
        },5000);
        System.out.println("计时开始");
    }
}
